﻿@using Flagrum.Web.Features.WorkshopMods.Data
@inject FlagrumDbContext Context
@inject ModelReplacementPresets ModelReplacementPresets
@inject NavigationManager Navigation
@inject IStringLocalizer<ModelReplacements> L
@inject IStringLocalizer<WorkshopMods.Index> ParentLocalizer

<CascadingValue Value="this">
    @if (Presets.Any(p => p.IsFavourite))
    {
        <h5 class="text-grey-300 mt-6 mb-4 ml-1">@L["FavouritePresets"]</h5>
        foreach (var preset in Presets.Where(p => p.IsFavourite))
        {
            <ModelReplacementRow Preset="preset"/>
        }
    }

    <h5 class="text-grey-300 mt-6 mb-4 ml-1">@L["FlagrumPresets"]</h5>

    @foreach (var preset in Presets.Where(p => !p.IsFavourite && p.IsDefault))
    {
        <ModelReplacementRow Preset="preset"/>
    }

    @if (Presets.Any(p => !p.IsDefault && !p.IsFavourite))
    {
        <h5 class="text-grey-300 mt-6 mb-4 ml-1">@L["CustomPresets"]</h5>

        @foreach (var preset in Presets.Where(p => !p.IsDefault && !p.IsFavourite))
        {
            <ModelReplacementRow Preset="preset"/>
        }
    }

    <div class="mb-2"></div>
</CascadingValue>

@code
{
    private List<ModelReplacementPresetMetadata> Presets { get; set; }

    protected override void OnInitialized()
    {
        var favourites = Context.ModelReplacementFavourites.ToList();

        var replacements = ModelReplacementPresets.GetDefaultReplacements();
        var defaults = replacements
            .Select(r => new ModelReplacementPresetMetadata
            {
                Id = r.Index,
                IsDefault = true,
                IsFavourite = favourites.Any(f => f.Id == r.Index && f.IsDefault),
                Name = ParentLocalizer[r.ModmetaName],
                Paths = r.Models
            })
            .ToList();

        var custom = Context.ModelReplacementPresets
            .Select(r => new ModelReplacementPresetMetadata
            {
                Id = r.Id,
                IsDefault = false,
                Name = r.Name,
                Paths = r.ReplacementPaths.Select(rp => rp.Path)
            })
            .ToList();

        foreach (var item in custom
            .Where(item => favourites
                .Any(f => f.Id == item.Id && !f.IsDefault)))
        {
            item.IsFavourite = true;
        }

        Presets = defaults
            .Union(custom)
            .OrderBy(r => r.IsFavourite)
            .ThenBy(r => r.Name)
            .ToList();
    }

    public void CallStateHasChanged()
    {
        StateHasChanged();
    }

    public void RemovePreset(int presetId)
    {
        var match = Presets.FirstOrDefault(p => !p.IsDefault && p.Id == presetId);
        if (match != null)
        {
            Presets.Remove(match);
            StateHasChanged();
        }
    }
}